package com.feeyo.prophet.controller;

import com.basho.riak.client.core.query.RiakObject;
import com.basho.riak.client.core.util.BinaryValue;
import com.feeyo.prophet.service.RiakService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.StringReader;
import java.nio.charset.StandardCharsets;

@Slf4j
@Controller
@RequestMapping("/files")
public class FilePreviewController {

    @Value("${riak.bucket}")
    private String bucket;
    private final RiakService riakService;

    public FilePreviewController(RiakService riakService) {
        this.riakService = riakService;
    }

    @GetMapping("/{filename:.+}")
    public ResponseEntity<Resource> previewFile(@PathVariable String filename) {
        try {
            String fileExtension = getFileExtension(filename);
            // 从 Riak 获取文件内容
            RiakObject riakObject = riakService.get(bucket, filename);
            if (riakObject == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            BinaryValue value = riakObject.getValue();
            byte[] fileContent = value.getValue();
            HttpHeaders headers = new HttpHeaders();
            if ("csv".equalsIgnoreCase(fileExtension)) {
                String fileContentStr = new String(fileContent, StandardCharsets.UTF_8);
                String htmlContent = convertCsvToHtmlTable(fileContentStr);
                byte[] encodedContent = htmlContent.getBytes(StandardCharsets.UTF_8);
                Resource resource = new ByteArrayResource(encodedContent);
                headers.add(HttpHeaders.CONTENT_TYPE, "text/html; charset=UTF-8");
                return new ResponseEntity<>(resource, headers, HttpStatus.OK);
            } else if ("png".equalsIgnoreCase(fileExtension)) {
                Resource resource = new ByteArrayResource(fileContent);
                headers.add(HttpHeaders.CONTENT_TYPE, "image/png");
                return new ResponseEntity<>(resource, headers, HttpStatus.OK);
            } else {
                // 其他文件类型处理
                return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).body(null);
            }
        } catch (Exception e) {
            log.error("文件下载失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf('.') == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf('.') + 1);
    }

    /**
     * CSV文件预览展示
     * @param csvContent
     * @return
     */
    private String convertCsvToHtmlTable(String csvContent) {
        StringBuilder htmlBuilder = new StringBuilder();
        htmlBuilder.append("<html><head><title>CSV Preview</title></head><body><table border='1'>");
        try {
            StringReader reader = new StringReader(csvContent);
            Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader);
            boolean isFirstRow = true;
            for (CSVRecord record : records) {
                if (isFirstRow) {
                    htmlBuilder.append("<thead><tr>");
                    for (String cell : record) {
                        htmlBuilder.append("<th>").append(cell).append("</th>");
                    }
                    htmlBuilder.append("</tr></thead><tbody>");
                    isFirstRow = false;
                } else {
                    htmlBuilder.append("<tr>");
                    for (String cell : record) {
                        htmlBuilder.append("<td>").append(cell).append("</td>");
                    }
                    htmlBuilder.append("</tr>");
                }
            }
            htmlBuilder.append("</tbody></table></body></html>");
        } catch (Exception e) {
            log.error("CSV 解析失败", e);
        }
        return htmlBuilder.toString();
    }
}
